﻿package kliment.utils {
	import flash.display.MovieClip;
	import flash.utils.setInterval;
	import flash.utils.clearInterval;
	/**
	 * ...
	 * @author	Kliment
	 * @version	1.0.1
	 * 
	 * class name: kliment.utils.RandomRun
	 */
	public class RandomRun {
		private var _randomList:RandomList;
		private var _isRaned:Array;
		private var _elements:Array;
		private var _interval:Number;
		private var _interval_id:uint;
	
		public function RandomRun(parent_mc:MovieClip, interval:Number, autostart:Boolean = true) {
			_interval = interval;
			_elements = new Array();
			_isRaned = new Array();
			var i:uint = parent_mc.numChildren;
			while(i--) {
				var item:* = parent_mc.getChildAt(i);
				if (item is MovieClip) {
					_elements.push(item);
					item.stop();	
				}
			}
			_randomList = new RandomList(0, _elements.length - 1);
			if (autostart)
				run();
		}
		
		public function run():void {
			if (_elements.length > 0)
				_next();
		}
		
		private function _next():void {
			clearInterval(_interval_id);
			var item_mc:MovieClip = _elements[_randomList.nextIndex];
			item_mc.play();
			_isRaned.push(item_mc);
			if (_randomList.remain > 0)
				_interval_id = setInterval(_next, _interval);
		}
		
		public function play():void {
			var i:Number = _isRaned.length;
			while (i--) {
				_isRaned[i].play();
			}
			_next();
		}
		
		public function stop():void {
			clearInterval(_interval_id);
			var i:Number = _isRaned.length;
			while (i--) {
				_isRaned[i].stop();
			}
		}
	}

}